<template>
  <div>
    <table
      border="1"
      width="700"
      style="border-collapse: collapse"
    >
      <caption>
        购物车
      </caption>
      <thead>
        <tr>
          <th>
            <input type="checkbox" :checked="isCheckedAll" @change="updateAllChecked"/> <span>全选</span>
          </th>
          <th>名称</th>
          <th>价格</th>
          <th>数量</th>
          <th>总价</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item,index) in shopList" :key="index">
          <td>
            <input type="checkbox" :checked="item.checked" @change="editChecked(item)"/>
          </td>
          <td>{{item.name}}</td>
          <td>{{item.price}}</td>
          <td>
            <button @click="updateCount(-1,item)">-</button>
            {{item.num}}
            <button @click="updateCount(1,item)">+</button>
          </td>
          <td>{{item.price*item.num}}</td>
          <td>
            <a href="javascript:;" @click="del(item)">删除</a>
          </td>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <td>合计:</td>
          <td colspan="5">
            {{num}}
          </td>
        </tr>
      </tfoot>
    </table>
  </div>
</template>

<script>
import {mapState,mapMutations,mapGetters} from 'vuex'
export default {
  data() {
    return {
    };
  },
  computed:{
    ...mapState('shop',['shopList']),
    ...mapGetters('shop',['total','num']),
    isCheckedAll(){
      return this.total === this.shopList.length
    }
  },
  created(){
    this.$store.dispatch('shop/getGoodsList')
  },
  methods:{
    ...mapMutations('shop',['del','editChecked','updateAll']),
    updateCount(num,item){
      const count = item.num+num
      if(count < 1) return
      this.$store.commit('shop/updateCount',{
        id:item.name,
        count
      })
    },
    updateAllChecked(){
      this.updateAll(!this.isCheckedAll)
    }
  }
};
</script>

<style>
</style>